<?php

namespace app\admin\controller\extension;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\admin\library\Auth;
/**
 * 商品列管理
 *
 * @icon fa fa-circle-o
 */
class Goods extends Backend
{

    /**
     * Goods模型对象
     * @var \app\admin\model\goods\Goods
     */
    protected $model = null;
    protected $personal_model = null;
    protected $admin_model = null;
    protected $order_model = null;
//    protected $extension_model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\goods\Goods;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->personal_model = new \app\admin\model\personal\Personal();
        $this->admin_model = new \app\admin\model\Admin();
        $this->order_model = new \app\admin\model\order\Order();
//        $this->extension_model = new \app\admin\model\extension\Extension();
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $auth = Auth::instance();
            $id = $auth->id;
            $mobile = $auth->mobile;
            //获取客服类型
//            $ke_type = \app\admin\model\Admin::where(['id'=>$id])->value('type');
            $power = DB::name("staff")->where("mobile",$mobile)->find();
            $access = \app\admin\model\AuthGroupAccess::where(['uid'=>$id])->find();
            $group = \app\admin\model\AuthGroup::where(['id'=>$access['group_id']])->find();
            if ($group['name'] == '组员') {
                $map['goods.invite'] = $power['invite'];
            } else {
                $map['goods.invite'] = array('not in','');
            }

            $list = $this->model
                ->with(['staff'])
                ->where('goods.status','neq',9)
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','goods_sn','gamename','type_name','title','price','plat','operator','invite','area','server','havetime','createtime','status','method']);
                $row->visible(['staff']);
                $row->getRelation('staff')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function add($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $auth = Auth::instance();
                    $mobile = $auth->mobile;
//                    $invite = \app\admin\model\Admin::where(['id'=>$id])->value('invite');
                    $invite = DB::name("staff")->where("mobile",$mobile)->value("invite");

                    $map['goods_sn'] = $params['goods_sn'];
                    $goods = Db::name('goods')->where('goods_sn',$params['goods_sn'])->find();
                    $order = Db::name('order')->where('goods_id',$goods['id'])->select();
                    if (!empty($order)) {
                        throw new Exception('此商品已交易，请通知组长进行补录');
                    }
                    if ($params['type'] == 1) {
                        if (empty($params['mobile']) && empty($params['qq']) && empty($params['g_account'])) {
                            throw new Exception('请输入商品信息');
                        }
                        if (!empty($params['mobile'])) {
                            $map['mobile'] = $params['mobile'];
                        }
                        if (!empty($params['qq'])) {
                            $map['qq'] = $params['qq'];
                        }
                        if (!empty($params['g_account'])) {
                            $map['g_account'] = $params['g_account'];
                        }
                        $g = Db::name('goods')->where($map)->find();
                        if (empty($g)) {
                            throw new Exception('商品信息不正确');
                        }
                        if (!empty($g['invite'])) {
                            if ($goods['invite'] != $invite) {
                                throw new Exception('此商品已被录入');
                            } else {
                                throw new Exception('此商品您已录入');
                            }
                        } else {
                            $par['invite'] = $invite;
                            $result = Db::name('goods')->where('goods_sn',$params['goods_sn'])->update($par);
                        }
                    } else {
                        $chat['lt_image'] = $params['lt_image'];
                        $chat['goods_sn'] = $params['goods_sn'];
                        $chat['goods_id'] = $goods['id'];
                        $chat['invite'] = $invite;
                        $chat['status'] = 1;
                        $result = Db::name('chat')->insert($chat);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 审核
     */
    public function edit($ids = null)
    {
        $get = $this->request->get("");
        if(count($get)>2){
            $ids = $this->order_model::where('id','=',$get['order_id'])->value('goods_id');
        }
        $row = $this->model->get($ids);
        // dump($sku);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            // dump($params);exit;
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function info($ids = null)
    {
        $get = $this->request->get("");
        if(count($get)>2){
            $ids = $this->order_model::where('id','=',$get['order_id'])->value('goods_id');
        }
        $row = $this->model->get($ids);
        $images = [];
        if (!$row) {
            $this->error(__('No Results were found'));
        }else{
            if($row['images']){
                $images = explode(",",$row['images']);
            }
        }
        $row['personal'] = $this->personal_model::where('id', '=', $row['uid'])
            ->field('account,nickname,is_real,id_card,name')->find();
        $sku = htmlspecialchars_decode($row['sku']);
        // dump($sku);
        $sku = json_decode($sku,true);
        // dump($sku);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $this->view->assign("row", $row);
        $this->view->assign("sku", $sku);
        $this->view->assign("images", $images);
        return $this->view->fetch();
    }


    /**
     * 获取
     */
    public function search()
    {
        $order = $_GET['order_sn'];
        $info =Db::name("goods")->where("goods_sn",$order)->find();
        if($info){
            $data = array(
                'gamename'=>$info['gamename'],
                'server'=>$info['server']
            );
            echo json_encode($data);
        }else{
            $this->error("error");
        }
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $count = 0;
            Db::startTrans();
            try {
                $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
                $values['invite'] = '';
                foreach ($list as $index => $item) {
                    $count += $item->allowField(true)->isUpdate(true)->save($values);
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


    /**
     * 补录
     */
    public function enter($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $auth = Auth::instance();
                    $mobile = $auth->mobile;
                    $invite = DB::name("staff")->where("mobile",$mobile)->value("invite");

                    $map['goods_sn'] = $params['goods_sn'];
                    $goods = Db::name('goods')->where('goods_sn',$params['goods_sn'])->find();
//                    if ($params['type'] == 1) {
                        if (empty($params['mobile']) && empty($params['qq']) && empty($params['g_account'])) {
                            throw new Exception('请输入商品信息');
                        }
                        if (empty($params['invite'])) {
                            throw new Exception('请输入员工工号');
                        }
                        if (!empty($params['mobile'])) {
                            $map['mobile'] = $params['mobile'];
                        }
                        if (!empty($params['qq'])) {
                            $map['qq'] = $params['qq'];
                        }
                        if (!empty($params['g_account'])) {
                            $map['g_account'] = $params['g_account'];
                        }
                        $g = Db::name('goods')->where($map)->find();
                        if (empty($g)) {
                            throw new Exception('商品信息不正确');
                        }
                        $par['invite'] = $params['invite'];
                        $result = Db::name('goods')->where('goods_sn',$params['goods_sn'])->update($par);
//                    } else {
//                        $chat['lt_image'] = $params['lt_image'];
//                        $chat['goods_sn'] = $params['goods_sn'];
//                        $chat['goods_id'] = $goods['id'];
//                        $chat['invite'] = $invite;
//                        $chat['status'] = 1;
//                        $result = Db::name('chat')->insert($chat);
//                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

}
